Hyunjung Im
Frontend Developer
2022-12-28
Insertion | O(1) |
Removal | O(1) |
Searching | O(N) |
Access | O(N) |
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
push(val) {
const newNode = new Node(val);
this.size++;
if (!this.first) {
this.first = newNode;
this.last = newNode;
} else {
const temp = this.first;
this.first = newNode;
this.first.next = temp;
}
return ++this.size;
}
pop() {
if (!this.first) {
return null;
}
if (!this.size) {
this.last = null;
}
const temp = this.first;
this.first = this.first.next;
this.size--;
return temp.value;
}
}
Insertion | O(1) |
Removal | O(1) |
Searching | O(N) |
Access | O(N) |
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
enqueue(value) {
const newNode = new Node(value);
if (!this.size) {
this.first = newNode;
this.last = newNode;
} else {
this.last.next = newNode;
this.last = newNode;
}
return ++this.size;
}
dequeue() {
if (!this.size) return null;
if (this.size === 1) {
this.last = null;
}
const temp = this.first;
this.first = this.first.next;
this.size--;
return temp.value;
}
}